<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas 绘制鼠标路径</title>
  <style>
    body {
      display: flex;
      align-items: center;
      height: 100vh;
      justify-content: center;
    }
    canvas {
      border: 1px solid black;
      cursor: crosshair;
      
    }
  </style>
</head>
<body>

<canvas id="myCanvas" width="600" height="400"></canvas>

<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
  let isDrawing = false; // 标志是否正在绘制

  // 获取鼠标在 canvas 上的相对位置
  function getMousePos(event) {
    const rect = canvas.getBoundingClientRect();
    return {
      x: event.clientX - rect.left,
      y: event.clientY - rect.top
    };
  }

  // 鼠标按下，开始绘制
  canvas.addEventListener('mousedown', (event) => {
    isDrawing = true;
    const pos = getMousePos(event);
    console.log(pos)
    // 开始新的路径
    ctx.beginPath();
    ctx.moveTo(pos.x, pos.y); // 把路径起点移动到鼠标的初始位置
  });

  // 鼠标移动，绘制路径
  canvas.addEventListener('mousemove', (event) => {
    if (isDrawing) {
      const pos = getMousePos(event);
      
      // 跟踪鼠标移动，绘制路径
      ctx.lineTo(pos.x, pos.y);
      ctx.stroke(); // 进行描边
    }
  });

  // 鼠标抬起，停止绘制
  canvas.addEventListener('mouseup', () => {
    isDrawing = false;
  });

  // 鼠标离开 canvas，停止绘制
  canvas.addEventListener('mouseleave', () => {
    isDrawing = false;
  });
</script>

</body>
</html>
